
const tableName = "BillProject";
let getProjects = (uid, cb) => {
  let Project = new wx.BaaS.TableObject(tableName),
    query = new wx.BaaS.Query()

  query.compare('created_by', '=', uid)
  query.compare('is_delete', '=', false)
  Project.setQuery(query).limit(1000).orderBy(['-created_at']).expand(['created_by']).find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}
let getCanProjects = (uid, cb) => {
  let Project = new wx.BaaS.TableObject(tableName),
    query = new wx.BaaS.Query()

  query.compare('created_by', '=', uid)
  query.compare('is_delete', '=', false)
  query.compare('is_end', '=', false)
  Project.setQuery(query).limit(1000).orderBy(['-created_at']).expand(['created_by']).find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}
let getProject = (projectId, cb) => {
  let Project = new wx.BaaS.TableObject(tableName);

  Project.get(projectId).then(res => cb(res))
    .catch(err => console.dir(err))
}

let addProject = (project_name, cb) => {
  let Projects = new wx.BaaS.TableObject(tableName),
    Project = Projects.create()

  let data = {
    project_name
  }

  Project.set(data)
    .save()
    .then(res => cb(res))
    .catch(err => console.dir(err))

}

let updateProject = (id, project_name,  cb) => {
  let Projects = new wx.BaaS.TableObject(tableName),
    Project = Projects.getWithoutData(id)

  let data = {
    project_name
  }

  Project.set(data)
    .update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}
let endProject = (id, cb) => {
  let Projects = new wx.BaaS.TableObject(tableName),
    Project = Projects.getWithoutData(id)
  Project.set("is_end", true)
  Project.set("end_time", ((new Date()).toISOString()).toString())
  Project.update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let startProject = (id, cb) => {
  let Projects = new wx.BaaS.TableObject(tableName),
    Project = Projects.getWithoutData(id)
  Project.set("is_end", false)
  Project.set("end_time", null)
  Project.update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let deleteProject = (id, cb) => {
  let Projects = new wx.BaaS.TableObject(tableName),
    Project = Projects.getWithoutData(id)
  Project.set("is_delete", true)
  Project.update()
    .then(res => cb(res))
    .catch(err => console.dir(err))

  // let Projects = new wx.BaaS.TableObject(tableName)

  // Projects.delete(id)
  //   .then(res => cb(res))
  //   .catch(err => console.dir(err))
}

module.exports = {
  getProjects,
  getCanProjects,
  getProject,
  addProject,
  updateProject,
  deleteProject,
  endProject,
  startProject
}